package com.zs.toolbox.web2j.common.web;

import com.zs.toolbox.web2j.common.exception.WtBaseException;
import com.zs.toolbox.web2j.common.exception.WtResponses;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.ConstraintViolation;
import javax.validation.Validator;
import java.util.Set;

/**
 * @author shuai.zhang  on 2018/9/21
 * @version 1.0.0
 * @description
 */
@Slf4j
public class WtBaseController {


    @Autowired
    private Validator validate;

    public void volidate(Object params) {

        Set<ConstraintViolation<Object>> validate = this.validate.validate(params);
        for (ConstraintViolation<Object> objectConstraintViolation : validate) {
            throw new WtBaseException(objectConstraintViolation.getMessage(), WtResponses.E_PARAM.getStatus());
        }

    }

    /**
     * Gets request.
     *
     * @return the request
     */
    protected HttpServletRequest getRequest() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
    }


    public String getRemoteIP() {
        HttpServletRequest request = getRequest();
        String ip = request.getHeader("X-real-ip");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        return ip.equals("0:0:0:0:0:0:0:1") ? "127.0.0.1" : ip;
    }

    /**
     * Gets response.
     *
     * @return the response
     */
    protected HttpServletResponse getResponse() {
        return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
    }

    protected String getServletPath() {
        return getRequest().getServletPath();
    }

    protected String getCompleteURL() {
        return getRequest().getRequestURL().toString();
    }

    protected String getCompleteURI() {
        return String.format("%s?%s", getRequest().getRequestURI(), getRequest().getQueryString());
    }
}
